/*
 * EmployeeReports.java
 *
 * Created on 4 December 2006, 13:12
 */

package org.foment.gem.beans;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
import org.foment.gem.dialogs.GemInternalDialog;
import org.foment.gem.dialogs.ReportPrepareDialog;
import static org.foment.joliage3.core.internationalization.Internationalization.i18n;
import org.foment.joliage3.reports.Report;
import org.foment.joliage3.sql.Database;
import org.foment.joliage3.sql.Table;

/**
 *
 * @author  ivan
 */
public class EmployeeReports extends javax.swing.JPanel implements Table.TableListener {
  
  private javax.swing.DefaultListModel newReportsModel, reportsArchiveModel;

  public void update() {
    try {
      lblEmployee.setText(
        "<html>(" + Database.getTable("Employee").getResultSet().getString("EmployeeID") + ") " +
        "<b>" + Database.getTable("Employee").getResultSet().getString("EmployeeSurname") + ", " +
        Database.getTable("Employee").getResultSet().getString("EmployeeFirstName") + "</b>"
      );
      _EmployeeID = Database.getTable("Employee").getResultSet().getInt("EmployeeID");
      updateLists();
      setVisible(true);
    } catch (SQLException ex) {
      _EmployeeID = -1;
      setVisible(false);
    }
  }
  
  private void updateLists() {
    updateNewReportsList();
    updateReportsArchiveList();
  }
  
  private void updateNewReportsList() {
    if (_EmployeeID == -1) return;
    try {
      String query = "SELECT ReportID FROM JobTypeReport AS JTR, EmployeeJobType AS EJT WHERE " +
        "JTR.JobTypeID = EJT.JobTypeID AND EJT.EmployeeID = '" + _EmployeeID + "';";

      Connection conn = Database.getConnection();
      ResultSet rs = conn.createStatement().executeQuery(query);
      
      newReportsModel.clear();
      
      HashMap<String, String> hm = new HashMap();
      hm.put("EmployeeID", String.valueOf(_EmployeeID));
      
      while (rs.next()) {
        newReportsModel.addElement(Report.createNewReport(rs.getInt("ReportID"), hm));
      }
      
      rs.close();
      conn.close();
    } catch (SQLException ex) {
      // Nothing
    }
  }

  private void updateReportsArchiveList() {
    if (_EmployeeID == -1) return;
    try {
      String query = "SELECT RC.ReportCacheID FROM ReportCache RC, EmployeeReportCache ERC WHERE " +
        "RC.ReportCacheID = ERC.ReportCacheID AND ERC.EmployeeID = '" + _EmployeeID + "' ORDER BY ReportCacheTimestamp DESC;";

      Connection conn = Database.getConnection();
      ResultSet rs = Database.getConnection().createStatement().executeQuery(query);
      
      reportsArchiveModel.clear();
      
      while (rs.next()) {
        reportsArchiveModel.addElement(Report.loadReportFromCache(rs.getInt("ReportCacheID")));
      }
      
      rs.close();
      conn.close();
    } catch (SQLException ex) {
      ex.printStackTrace();
    }
  }

  /** Creates new form BeanForm */
  public EmployeeReports() {
    initComponents();
    
    setVisible(false);
    
    newReportsModel = new javax.swing.DefaultListModel();
    lstNewReports.setModel(newReportsModel);
    lstNewReports.setCellRenderer(new ReportItemRenderer());
    
    reportsArchiveModel = new javax.swing.DefaultListModel();
    lstReportsArchive.setModel(reportsArchiveModel);
    lstReportsArchive.setCellRenderer(new ArchivedReportItemRenderer());

    try {
      Database.getTable("EmployeeReportCache").addListener(this);
      Database.getTable("ReportCache").addListener(this);
      Database.getTable("Report").addListener(this);
    } catch (SQLException ex) {
      
    }
  }
  
  /** This method is called from within the constructor to
   * initialize the form.
   * WARNING: Do NOT modify this code. The content of this method is
   * always regenerated by the Form Editor.
   */
  // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
  private void initComponents() {
    txtBorder = new javax.swing.JTextField();
    lblNewReport = new javax.swing.JLabel();
    scrollNewReports = new javax.swing.JScrollPane();
    lstNewReports = new javax.swing.JList();
    lblReportsArchive = new javax.swing.JLabel();
    scrollReportsArchive = new javax.swing.JScrollPane();
    lstReportsArchive = new javax.swing.JList();
    pnlEmployee = new javax.swing.JPanel();
    lblEmployee = new javax.swing.JLabel();

    txtBorder.setText("jTextField1");

    lblNewReport.setText(i18n("Print a new report: (Click to print)"));

    scrollNewReports.setBorder(txtBorder.getBorder());
    scrollNewReports.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
    scrollNewReports.setMaximumSize(new java.awt.Dimension(32767, 200));
    scrollNewReports.setMinimumSize(new java.awt.Dimension(25, 100));
    scrollNewReports.setPreferredSize(new java.awt.Dimension(260, 150));
    lstNewReports.addMouseListener(new java.awt.event.MouseAdapter() {
      public void mouseClicked(java.awt.event.MouseEvent evt) {
        lstNewReportsMouseClicked(evt);
      }
    });

    scrollNewReports.setViewportView(lstNewReports);

    lblReportsArchive.setText(i18n("Print a report from archives: (Click to print)"));

    scrollReportsArchive.setBorder(txtBorder.getBorder());
    scrollReportsArchive.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
    scrollReportsArchive.setMaximumSize(new java.awt.Dimension(32767, 200));
    scrollReportsArchive.setMinimumSize(new java.awt.Dimension(25, 100));
    scrollReportsArchive.setPreferredSize(new java.awt.Dimension(260, 150));
    lstReportsArchive.addMouseListener(new java.awt.event.MouseAdapter() {
      public void mouseClicked(java.awt.event.MouseEvent evt) {
        lstReportsArchiveMouseClicked(evt);
      }
    });

    scrollReportsArchive.setViewportView(lstReportsArchive);

    lblEmployee.setFont(new java.awt.Font("Dialog", 0, 12));
    lblEmployee.setText(".");

    org.jdesktop.layout.GroupLayout pnlEmployeeLayout = new org.jdesktop.layout.GroupLayout(pnlEmployee);
    pnlEmployee.setLayout(pnlEmployeeLayout);
    pnlEmployeeLayout.setHorizontalGroup(
      pnlEmployeeLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
      .add(pnlEmployeeLayout.createSequentialGroup()
        .addContainerGap()
        .add(lblEmployee, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 512, Short.MAX_VALUE)
        .addContainerGap())
    );
    pnlEmployeeLayout.setVerticalGroup(
      pnlEmployeeLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
      .add(pnlEmployeeLayout.createSequentialGroup()
        .addContainerGap()
        .add(lblEmployee)
        .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );

    org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
    this.setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
      .add(pnlEmployee, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
      .add(layout.createSequentialGroup()
        .addContainerGap()
        .add(lblNewReport, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 512, Short.MAX_VALUE)
        .addContainerGap())
      .add(layout.createSequentialGroup()
        .addContainerGap()
        .add(scrollNewReports, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 512, Short.MAX_VALUE)
        .addContainerGap())
      .add(layout.createSequentialGroup()
        .addContainerGap()
        .add(lblReportsArchive, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 512, Short.MAX_VALUE)
        .addContainerGap())
      .add(layout.createSequentialGroup()
        .addContainerGap()
        .add(scrollReportsArchive, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 512, Short.MAX_VALUE)
        .addContainerGap())
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
      .add(layout.createSequentialGroup()
        .add(pnlEmployee, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
        .add(lblNewReport)
        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
        .add(scrollNewReports, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
        .add(lblReportsArchive)
        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
        .add(scrollReportsArchive, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 249, Short.MAX_VALUE)
        .addContainerGap())
    );
  }// </editor-fold>//GEN-END:initComponents

  private void lstReportsArchiveMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lstReportsArchiveMouseClicked
    if (lstReportsArchive.getSelectedIndex() != -1) {
      printReport((Report) lstReportsArchive.getSelectedValue());
    }

    lstReportsArchive.clearSelection();
  }//GEN-LAST:event_lstReportsArchiveMouseClicked

  private void addEmployeeReportCache(Report report, int employeeID) {
    if (report.getReportCacheID() != -1) {
      try {
        Database.getTable("EmployeeReportCache").pushState();
        //Database.getTable("EmployeeReportCache").getResultSet().moveToInsertRow();
        Database.getTable("EmployeeReportCache").getResultSet().updateInt("EmployeeID", _EmployeeID);
        Database.getTable("EmployeeReportCache").getResultSet().updateInt("ReportCacheID", report.getReportCacheID());
        Database.getTable("EmployeeReportCache").insertRow();
        Database.getTable("EmployeeReportCache").popState();
      } catch (SQLException ex) {
        ex.printStackTrace();
      }        
    }
  }
  
  private void printReport(Report report) {
    if (report == null) return;
    //if (report.getPaper() != null) {
      ReportPrepareDialog rpd = new ReportPrepareDialog(report);
      rpd.setExtraData(new Integer(_EmployeeID));

      GemInternalDialog.getMainDesktopPane().add(rpd);

      rpd.addInternalFrameListener(
        new InternalFrameAdapter() {
          public void internalFrameClosed(InternalFrameEvent internalFrameEvent) {
            Report rpd_report = ((ReportPrepareDialog) internalFrameEvent.getInternalFrame()).getReport();
            Integer rpd_employeeID = (Integer) (((ReportPrepareDialog) internalFrameEvent.getInternalFrame()).getExtraData());
            addEmployeeReportCache( rpd_report, rpd_employeeID.intValue());
          }
        }
      );

      rpd.setSize(GemInternalDialog.getMainDesktopPane().getSize());
      rpd.setVisible(true);
    /*} else {
      int archive = org.foment.joliage3.newt.Question.showQuestion(
        i18n("Archive"),
        i18n("Do you also want to save the report to the archive after printing?"),
        i18n("Yes"),
        i18n("No")
      ); // == org.foment.joliage3.newt.Question.STATUS_YES);
      if (archive == org.foment.joliage3.newt.Question.STATUS_UNDEFINED) return;
      report.print(archive == org.foment.joliage3.newt.Question.STATUS_YES);
      addEmployeeReportCache(report, _EmployeeID);
    }*/
  }
  
  private void lstNewReportsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lstNewReportsMouseClicked
    if (lstNewReports.getSelectedIndex() != -1) {
      printReport((Report) lstNewReports.getSelectedValue());
    }
    lstNewReports.clearSelection();
  }//GEN-LAST:event_lstNewReportsMouseClicked

  public void tableRowDeleted(Table table, int row) {
    tableDataChanged(table);
  }

  public void tableRowUpdated(Table table, int row) {
    tableDataChanged(table);
  }

  public void tableRowInserted(Table table) {
    tableDataChanged(table);
  }

  public void tableDataChanged(Table table) {
    if (table.getTableName().equals("Report"))
      updateNewReportsList();
    else if (table.getTableName().equals("ReportCache") || table.getTableName().equals("EmployeeReportCache"))
      updateReportsArchiveList();
  }
  
  
  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JLabel lblEmployee;
  private javax.swing.JLabel lblNewReport;
  private javax.swing.JLabel lblReportsArchive;
  private javax.swing.JList lstNewReports;
  private javax.swing.JList lstReportsArchive;
  private javax.swing.JPanel pnlEmployee;
  private javax.swing.JScrollPane scrollNewReports;
  private javax.swing.JScrollPane scrollReportsArchive;
  private javax.swing.JTextField txtBorder;
  // End of variables declaration//GEN-END:variables
  
  private int _EmployeeID = -1;
  
  private class ReportItemRenderer extends javax.swing.JTextPane implements javax.swing.ListCellRenderer {
    public ReportItemRenderer() {
      setBorder(new javax.swing.border.EmptyBorder(6, 6, 6, 6));
    
      setContentType("text/html");
      setFont(new java.awt.Font("Dialog", 0, 12));
    }
    
    protected String getText(Object value) {
      //ReportItem report = (ReportItem)value;
      
      Report report = (Report)value;
      
      int width = scrollNewReports.getWidth() - 50;
      
      return "<html><body><table width=\"" + width + "\"><tr><td>" +
        "<font face=\"sans\" size=\"3\"><b>" + report.getTitle() + "</b></font><br>" +
        "<font face=\"sans\" size=\"2\">" + report.getDescription() + "</font></td></tr></table></body></html>";
    }
    
    public java.awt.Component getListCellRendererComponent(javax.swing.JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
      //setPreferredSize(list.getSize());
      setText(getText(value));
            
      if (isSelected) {
        setBackground(new java.awt.Color(157, 183, 212));
      } else {
        if (index % 2 == 0)
          setBackground(new java.awt.Color(255, 255, 255));
        else
          setBackground(new java.awt.Color(238, 246, 255));
      }
      
      return this;
    }
  }
  
  private class ArchivedReportItemRenderer extends ReportItemRenderer {
     
    public ArchivedReportItemRenderer() {
      super();
    }
    
    protected String getText(Object value) {
      Report report = (Report)value;
      
      String dateFormat;
      
      if (report.getDate() != null)
        dateFormat = java.text.DateFormat.getDateInstance(java.text.DateFormat.FULL).format(report.getDate());
      else
        dateFormat = i18n("Unknown date");
      
      int width = scrollNewReports.getWidth() - 50;
      
      return "<html><body>" +
        "<table width=\"" + width + "\"><tr><td>" +
        "<font face=\"sans\" size=\"3\"><b>" + report.getTitle() + "</b></font></td><td align=\"right\">" +
        "<font face=\"sans\" size=\"2\">" + dateFormat + "</font></td></tr>" +
        "<tr><td colspan=\"2\"><font face=\"sans\" size=\"2\">" + report.getDescription() + "</font>" +
        "</td></tr></table></body></html>";

    }  
    
  }
}
